<template>
  <div class="user-stats-container">
    <div class="header">
      <h2>用户统计</h2>
      <p>用户系统整体运行状态和统计信息</p>
    </div>
    
    <!-- 统计卡片 -->
    <el-row :gutter="20" class="stats-grid">
      <el-col :xs="12" :sm="6" :lg="6">
        <el-card class="stat-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-icon" :style="{ backgroundColor: '#409EFF20', color: '#409EFF' }">
              <i class="el-icon-user"></i>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ stats.totalUsers || 0 }}</div>
              <div class="stat-label">总用户数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :xs="12" :sm="6" :lg="6">
        <el-card class="stat-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-icon" :style="{ backgroundColor: '#67C23A20', color: '#67C23A' }">
              <i class="el-icon-user-solid"></i>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ stats.onlineUsers || 0 }}</div>
              <div class="stat-label">在线用户</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :xs="12" :sm="6" :lg="6">
        <el-card class="stat-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-icon" :style="{ backgroundColor: '#E6A23C20', color: '#E6A23C' }">
              <i class="el-icon-circle-plus"></i>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ stats.newUsers || 0 }}</div>
              <div class="stat-label">新增用户</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :xs="12" :sm="6" :lg="6">
        <el-card class="stat-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-icon" :style="{ backgroundColor: '#F56C6C20', color: '#F56C6C' }">
              <i class="el-icon-star-off"></i>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ userGrowthRate }}%</div>
              <div class="stat-label">增长率</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 图表区域 -->
    <el-row :gutter="20" class="charts-row">
      <el-col :xs="24" :lg="12">
        <el-card class="chart-card" shadow="hover">
          <div slot="header" class="card-header">
            <span>用户增长趋势</span>
          </div>
          <div class="chart-container">
            <div ref="growthChart" class="chart-placeholder"></div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :xs="24" :lg="12">
        <el-card class="chart-card" shadow="hover">
          <div slot="header" class="card-header">
            <span>用户活跃度分布</span>
          </div>
          <div class="chart-container">
            <div ref="activityChart" class="chart-placeholder"></div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 用户角色分布 -->
    <el-row :gutter="20" class="charts-row">
      <el-col :xs="24">
        <el-card class="chart-card" shadow="hover">
          <div slot="header" class="card-header">
            <span>用户角色分布</span>
          </div>
          <div class="chart-container">
            <div ref="roleChart" class="chart-placeholder"></div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { mapActions } from 'vuex'
import * as echarts from 'echarts'

export default {
  name: 'UserStats',
  data() {
    return {
      stats: {
        totalUsers: 0,
        onlineUsers: 0,
        newUsers: 0
      },
      roleStats: {},
      growthStats: {},
      chartInstances: []
    }
  },
  computed: {
    userGrowthRate() {
      // 简单计算增长率
      if (this.stats.totalUsers > 0) {
        return ((this.stats.newUsers / this.stats.totalUsers) * 100).toFixed(2)
      }
      return 0
    }
  },
  async created() {
    await this.loadStats()
  },
  methods: {
    ...mapActions('users', ['fetchUserStats', 'fetchOnlineUsers', 'fetchNewUsers', 'fetchUserRoleStats', 'fetchUserGrowthStats']),
    async loadStats() {
      try {
        const [stats, roleStats, growthStats] = await Promise.all([
          this.fetchUserStats(),
          this.fetchUserRoleStats(),
          this.fetchUserGrowthStats()
        ])
        this.stats = stats
        this.roleStats = roleStats
        this.growthStats = growthStats
        this.$nextTick(() => {
          this.initCharts()
        })
      } catch (error) {
        this.$message.error('加载统计信息失败: ' + error.message)
      }
    },
    initCharts() {
      // 销毁现有的图表实例
      this.chartInstances.forEach(chart => {
        if (chart) {
          chart.dispose()
        }
      })
      this.chartInstances = []
      
      // 初始化增长趋势图表
      if (this.$refs.growthChart) {
        const growthChart = echarts.init(this.$refs.growthChart)
        this.chartInstances.push(growthChart)
        
        // 使用真实的用户增长数据
        const dates = Object.keys(this.growthStats.dailyStats || {})
        const userData = dates.map(date => this.growthStats.dailyStats[date])
        
        growthChart.setOption({
          tooltip: {
            trigger: 'axis'
          },
          xAxis: {
            type: 'category',
            data: dates
          },
          yAxis: {
            type: 'value'
          },
          series: [{
            data: userData,
            type: 'line',
            smooth: true,
            itemStyle: {
              color: '#409EFF'
            },
            areaStyle: {
              color: '#409EFF20'
            }
          }]
        })
      }
      
      // 初始化活跃度分布图表
      if (this.$refs.activityChart) {
        const activityChart = echarts.init(this.$refs.activityChart)
        this.chartInstances.push(activityChart)
        
        activityChart.setOption({
          tooltip: {
            trigger: 'item'
          },
          legend: {
            bottom: '0%',
            left: 'center'
          },
          series: [
            {
              name: '用户活跃度',
              type: 'pie',
              radius: ['40%', '70%'],
              avoidLabelOverlap: false,
              itemStyle: {
                borderRadius: 10,
                borderColor: '#fff',
                borderWidth: 2
              },
              label: {
                show: false,
                position: 'center'
              },
              emphasis: {
                label: {
                  show: true,
                  fontSize: '18',
                  fontWeight: 'bold'
                }
              },
              labelLine: {
                show: false
              },
              data: [
                { value: this.stats.onlineUsers || 0, name: '在线用户' },
                { value: (this.stats.totalUsers || 0) - (this.stats.onlineUsers || 0), name: '离线用户' }
              ]
            }
          ]
        })
      }
      
      // 初始化角色分布图表
      if (this.$refs.roleChart) {
        const roleChart = echarts.init(this.$refs.roleChart)
        this.chartInstances.push(roleChart)
        
        // 使用真实的用户角色分布数据
        const roleData = Object.keys(this.roleStats).map(role => ({
          name: role === 'ADMIN' ? '管理员' : '普通用户',
          value: this.roleStats[role]
        }))
        
        roleChart.setOption({
          tooltip: {
            trigger: 'item'
          },
          legend: {
            bottom: '0%',
            left: 'center'
          },
          series: [
            {
              name: '用户角色',
              type: 'pie',
              radius: ['40%', '70%'],
              avoidLabelOverlap: false,
              itemStyle: {
                borderRadius: 10,
                borderColor: '#fff',
                borderWidth: 2
              },
              label: {
                show: false,
                position: 'center'
              },
              emphasis: {
                label: {
                  show: true,
                  fontSize: '18',
                  fontWeight: 'bold'
                }
              },
              labelLine: {
                show: false
              },
              data: roleData
            }
          ]
        })
      }
    }
  }
}
</script>

<style scoped>
.user-stats-container {
  padding: 20px;
}

.header {
  margin-bottom: 30px;
}

.header h2 {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin: 0 0 10px 0;
}

.header p {
  font-size: 14px;
  color: #606266;
  margin: 0;
}

.stats-grid {
  margin-bottom: 30px;
}

.stat-card {
  border-radius: 10px;
  overflow: hidden;
  transition: all 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1) !important;
}

.stat-content {
  display: flex;
  align-items: center;
  padding: 20px;
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 20px;
  font-size: 24px;
}

.stat-info {
  flex: 1;
}

.stat-value {
  font-size: 28px;
  font-weight: bold;
  color: #303133;
  line-height: 1;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

.charts-row {
  margin-bottom: 30px;
}

.chart-card {
  margin-bottom: 20px;
  border-radius: 10px;
  overflow: hidden;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 600;
  font-size: 16px;
}

.chart-container {
  height: 350px;
  position: relative;
}

.chart-placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f5f7fa;
  border-radius: 4px;
  color: #909399;
}

.chart-placeholder::before {
  content: "图表加载中...";
}

@media (max-width: 768px) {
  .stats-grid {
    .el-col {
      margin-bottom: 15px;
    }
  }
  
  .stat-card {
    .stat-content {
      padding: 15px;
    }
    
    .stat-icon {
      width: 50px;
      height: 50px;
      margin-right: 15px;
      font-size: 20px;
    }
    
    .stat-value {
      font-size: 24px;
    }
  }
  
  .chart-container {
    height: 300px;
  }
}
</style>